class TrainProgrammeMgrController {
    def authenticateService

    def list = {
            // 找到最近的学校 学期教学计划 Term
            def current = new Date()
            def lastTerm = Term.withCriteria{
                and {
                    le('startTime' , current)
                    ge('endTime' , current)
                    eq('school' , session.school)
                } 
                maxResults(1)
            }
            
            log.info "TrainProgrammeMgr.index lastTerm = ${lastTerm}"
            if (lastTerm) {
                lastTerm = lastTerm[0]

//                找出所有已经编写的教学计划

                def trainProgrammeList = TrainProgramme.withCriteria {
                    and{
                        eq('teacher' , authenticateService?.userDomain()) 
                        eq('classes' , Classes.get(params.id)) 
                        eq('course' , params.course) 
                        eq('school' , session.school) 
                        eq('term' , lastTerm) 
                    } 
                }  

// 计算本学期的所有周，为显示教学计划

                def calendar = Calendar.getInstance()
                calendar.setFirstDayOfWeek(Calendar.MONDAY)
                calendar.setTime(lastTerm.startTime)

                def weeks = [] 
                def index = 1
                while(true){
                    
                    calendar.set(Calendar.DAY_OF_WEEK,   Calendar.MONDAY);
                    def first = calendar.getTime()
                    calendar.set(Calendar.DAY_OF_WEEK,   Calendar.SUNDAY);
                                            
                    def last = calendar.getTime()
                    def tp = trainProgrammeList.find{
                        it.week == index
                    }
                    weeks.add(['first' : first , 'last' : last , 'trainProgramme' : tp])
                    if (calendar.getTime().compareTo(lastTerm.endTime) > 0) {
                        break
                    }
                    calendar.add(Calendar.WEEK_OF_YEAR,   1)
                    index++
                }
                if (!weeks.isEmpty()) {
                    weeks[0].first = lastTerm.startTime
                    weeks[weeks.size()-1].last = lastTerm.endTime
                }
//                检查计算本学期周期的结果
//                weeks.each{
//                    println it.first.format('yyyy-MM-dd')
//                    println it.last.format('yyyy-MM-dd')
//                    println '=================='
//                }
                trainProgrammeList.clear()
                ['lastTerm' : lastTerm  , 'weeks' : weeks,
                 'classesid' : params.id,
                 'classesname' :  Classes.get(params.id),
                'course' : params.course  ]
            }else{
                flash.message = "没有最近的学校教学计划，所以暂时不需要编写教学计划。"
            }
    }
}
